package bid

import (
	"context"
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/process/common"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	"github.com/lishimeng/go-log"
	"time"
)

func SyncCampaigns(ctx context.Context) {
	startTime := time.Now()
	log.Info("start sync campaigns")
	common.TravelAmazonClients(ctx, syncCampaignListForOrg)
	endTime := time.Now()
	cost := endTime.Sub(startTime)
	log.Info("sync total sp campaign done, [%f seconds]", cost.Seconds())
}

func syncCampaignListForOrg(ctx context.Context, lwa db.AmazonLwaCommon, handler *advertising.Client) {
	startTime := time.Now()
	common.TravelAmazonPage(func(token ...string) (nextToken string, err error) {
		return fetchCampaignPage(ctx, handler, token...)
	})
	endTime := time.Now()
	cost := endTime.Sub(startTime)
	log.Info("sync total sp campaign done, [%s][%f seconds]", lwa.Name, cost.Seconds())
	return
}

func fetchCampaignPage(ctx context.Context, handler *advertising.Client, token ...string) (nextToken string, err error) {
	select {
	case <-ctx.Done():
		return
	default:

	}
	req := advertising.CampaignListReq{
		MaxResults: 50,
	}
	req.StateFilter = &advertising.TextFilter{}
	req.StateFilter.Include = append(req.StateFilter.Include, "ENABLED")
	if len(token) > 0 {
		req.NextToken = token[0]
	}
	var resp advertising.CampaignListResp
	resp, err = handler.GetCampaigns(req)
	if err != nil {
		log.Info(err)
		return
	}
	var count = len(resp.Campaigns)

	log.Info("campaign: %d[%d]", count, resp.TotalResults)
	if count > 0 {
		saveCampaign("sp", resp.Campaigns)
	}
	nextToken = resp.NextToken
	return
}
